import logging
import sqlite3
from typing import List, Union

from src.models import (
    FormerGraduateRecord,
    FreshGraduateRecord,
    HistoryMailRecord,
)
from src.ui.sqlite_pagination_model import PaginationSortFilterProxyModel

logger = logging.getLogger(__name__)

def update_records_status(
    db_conn: sqlite3.Connection,
    benke_ids: List[str],
    shuoshi_ids: List[str],
    boshi_ids: List[str],
):
    benke_sql = """
        UPDATE benke_record
        SET archive_delivery_status = '已寄出'
        WHERE id = ?
    """
    shuoshi_sql = """
        UPDATE shuoshi_record
        SET archive_delivery_status = '已寄出'
        WHERE id = ?
    """
    boshi_sql = """
        UPDATE boshi_record
        SET archive_delivery_status = '已寄出'
        WHERE id = ?
    """
    try:
        db_conn.executemany(benke_sql, [(id,) for id in benke_ids])
        db_conn.executemany(shuoshi_sql, [(id,) for id in shuoshi_ids])
        db_conn.executemany(boshi_sql, [(id,) for id in boshi_ids])
        db_conn.commit()
    except sqlite3.Error as e:
        logger.error(f"更新记录状态时出错: {e}")
        db_conn.rollback()
        raise

def add_records_to_history(
    records: List[Union[FreshGraduateRecord, FormerGraduateRecord]],
    history_table: PaginationSortFilterProxyModel,
    source_table: PaginationSortFilterProxyModel,
    tracking_number_list: List[str],
    record_type: str,
):
    """
    处理添加一条记录到打印历史记录中。
    """
    history_mail_records = []
    for record, tracking_number in zip(records, tracking_number_list):
        if isinstance(record, FreshGraduateRecord):
            record.remark += record_type + "；"
            history_mail_record = HistoryMailRecord.from_fresh_graduate_record(
                record, tracking_number=tracking_number
            )
        elif isinstance(record, FormerGraduateRecord):
            record.remark += record_type + "；"
            history_mail_record = HistoryMailRecord.from_former_graduate_record(
                record, tracking_number=tracking_number
            )
        else:
            raise ValueError("未知的记录类型")
        history_mail_records.append(history_mail_record)
    benke_ids = [record.id for record in records if record.education_level == "本科"]
    shuoshi_ids = [record.id for record in records if record.education_level == "硕士"]
    boshi_ids = [record.id for record in records if record.education_level == "博士"]
    db_conn = history_table.sourceModel().conn
    update_records_status(
        db_conn,
        benke_ids,
        shuoshi_ids,
        boshi_ids,
    )
    history_table.update_or_insert_batch_models(history_mail_records)
    source_table.delete_batch_by_models(records)
